package com.example.bbs.kafka.consumer;

import com.alibaba.fastjson.JSON;
import com.example.bbs.domain.entity.Comment;
import com.example.bbs.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class CommentConsumer {

    @Autowired
    CommentService commentService;

    @KafkaListener(topics = "comment-insert")
    public void processInsert(ConsumerRecord consumerRecord) {
        if (Objects.isNull(consumerRecord) || Objects.isNull(consumerRecord.value())) {
            return;
        }
        //解析数据
        Comment comment = JSON.parseObject((String) consumerRecord.value(), Comment.class);
        //同步到数据库
        commentService.save(comment);
        log.info("评论Id为[" + comment.getCommentId() + "]," + "主题为[comment-insert]的消息消费成功!");
    }

    @KafkaListener(topics = "comment-update")
    public void processUpdate(ConsumerRecord consumerRecord) {
        if (Objects.isNull(consumerRecord) || Objects.isNull(consumerRecord.value())) {
            return;
        }
        //解析数据
        Comment comment = JSON.parseObject((String) consumerRecord.value(), Comment.class);
        //同步到数据库
        commentService.update(comment);
        log.info("评论Id为[" + comment.getCommentId() + "]," + "主题为[comment-update]的消息消费成功!");
    }
}
